/**
 * Created by Administrator on 2016/7/25 0025.
 */
var AppService = {
  urlroot: "http://euvee.vicp.co/rest/task/",
  init: function () {
    Vue.http.options.root = this.urlroot;
    // Vue.http.options.emulateHTTP = true;
    Vue.http.headers.common['Token'] = window.localStorage.getItem('Token');
    //Vue.http.options.emulateJSON = true;
  },
  find: function (inputQuery, pagenum, pagesteps, items, success_callback, error_callback) {
    var url = this.urlroot;
    Vue.http.get(url, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    })
  },
  find2: function (criterion, pagenum, pagesteps, success_callback, error_callback) {
    Vue.http.get(this.urlroot + "?criterion=" + criterion + "&pagenum=" + pagenum + "&pagesteps=" + pagesteps, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    });
  },

  find3: function (id, success_callback, error_callback) {
    Vue.http.get(this.urlroot + id, function (data, status, request) {
      success_callback(data, status, request)
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request)
      }
    });
  },
//
  edit: function (id, item, success_callback, error_callback) {
    Vue.http.put(this.urlroot + id, item, function (data, status, request) {
      success_callback(data, status, request)
    }).catch(function (data, status, request) {
      error_callback(data, status, request)
    })
  },
  //返回父级目录
  backToParent: function (p, success_callback, error_callback) {
    Vue.http.get(this.urlroot + p + "/children", function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
        if (error_callback != null) {
          error_callback(data, status, request);
        }
      }
    );
  },
  backToParent2: function (parentid, success_callback, error_callback) {
    Vue.http.get(this.urlroot + parentid, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
        if (error_callback != null) {
          error_callback(data, status, request);
        }
      }
    );
  },
  //切换节点
  change: function (item, success_callback, error_callback) {
    Vue.http.get(this.urlroot + item.id, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
        if (error_callback != null) {
          error_callback(data, status, request);
        }
      }
    );
  },

  add: function (item, success_callback, error_callback) {
    Vue.http.post(this.urlroot, item, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    });
  },
  remove: function (item, success_callback, error_callback) {
    //	Vue.http.delete({id:id}, success_callback).error(error_callback);
    Vue.http.delete(this.urlroot + item.id, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    })
  }
};
var svc = Object.create(AppService);
/*Vue.component('my-component', {
 template: '<div>A custom component!</div>'
 });*/
Vue.component('itemlist', {
  template: '#itemlist-tpl',
  mode: "modeList",

  props: {
    items: {
      type: Object,
      twoWay: false,
      required: true
    },
    mode: {
      type: String,
      default: 'modeList'
    },
    onEdit: {
      type: Function,
      required: true
    },
    pagenum: {
      type: String,
      required: true
    },
    onRemove: {
      type: Function,
      required: true
    }
  },

  components: {
    //list: { /* ... */ },
    //itemviewer: { /* ... */ },
    //'itemlist': itemeditor,
  },
  data: function () {
    return {
      result: null,
    }
  },

  methods: {
    onEditItem: function (item, e) {
      console.log("onSubmitClick: inside component itemelist");
      console.log("editor list" + item);

      //this.result = this.onSubmit(this.mode, this.item);
      this.result = this.onEdit(item, this.mode);
    },
    onRemoveItem: function (item, e) {
      console.log("onRemoveClick: inside component itemelist");
      vm.onRemoveItem(item, this.mode);
    },
    onPagenum: function () {
      console.log("onPagenum: inside component itemelist");
      vm.pagenum = this.pagenum
      vm.__find('', this.pagenum, '');
    },
    onDetailsItem: function (mode, item) {
      console.log("onDetailsItem: inside component itemelist");
      vm.curitem = item;
      vm.setMode(mode);
    },
    backToParent: function (item) {
      console.log("backToParent: inside component itemelist");
      vm.backToParent(item);
    }
  },
  ready: function () {
  }
});
//Vue.component('my-component', MyComponent)
Vue.component('itemsearch', {
  template: '#itemsearch-tpl',
  mode: "modeSearch",
  props: {
    item: {
      type: Object,
      twoWay: false,
      required: true
    },
    onRemove: {
      type: Function,
      required: true
    }
  },
  data: function () {
    return {
      result: null
    }
  },
  methods: {
    onAdd: function () {
      console.log("setMode: inside component itemsearch");
      vm.setMode("modeAddNew");
    },
    onRemoveSelected: function () {
      var items = vm.items;
      var r = confirm("确定删除选中任务？");
      if (r == true) {
        for (var i in items) {
          if (items[i].selected) {
            svc.remove(items[i], function (data, status, request) {
              vm.__find('', vm.pagenum, 6);
            })
          }
        }
      }
    }
  }
});// ------end Vue.component('itemsearch')


Vue.component('itemeditor', {
  template: '#itemeditor-tpl',
  mode: "modeEdit",

  props: {
    item: {
      type: Object,
      twoWay: false,
      required: true
    },

    mode: {
      type: String,
      default: 'modeList'
    },
    onSubmit: {
      type: Function,
      required: true
    },
    onCancel: {
      type: Function,
      required: true
    }
  },

  data: function () {
    return {
      result: null,
    }
  },

  methods: {
    onSubmitClick: function (e) {
      console.log("onSubmitClick: inside component itemeditor");
      // if (typeof callabck == "function")
      //	callback(items);
      console.log(typeof this.onSubmit);

      //this.result = this.onSubmit(this.mode, this.item);
      this.result = this.onSubmit(this.mode, this.item);
    },
    onCancelClick: function (e) {
      console.log("onCancelClick: inside component itemeditor");
      this.onCancel(this.mode, this.item);
    }
  },
  ready: function () {
    // this.onLoad('message from child!')
  }
});

Vue.component('itemdetails', {
  template: '#itemdetails-tpl',
  mode: "modeDetails",

  props: {
    items2: {
      type: Object,
      twoWay: false,
      required: true
    },

    mode: {
      type: String,
      default: 'modeList'
    },
    onCancel: {
      type: Function,
      required: true
    }
  },

  data: function () {
    return {
      result: null
    }
  },
  methods: {
    onCancelClick: function (e) {
      console.log("onCancelClick: inside component itemdetails");
      this.onCancel(this.mode, this.item);
    }
  }
});

var vm = new Vue({
  el: '#app',
  data: {
    currentView: 'itemeditor',
    criterion: '',
    pagenum: '',
    pagesteps: '',
    midname: '',
    lastname: '',
    remotedevice: '',
    searchQuery: '',
    items: [],
    curitem: {},
    selectall: true,
    mode: 'modeList', // modeList, modeItemView, modeAddNew, modeEdit
    modeTitle: "",
    showModal: false,
    parentMsg: "test",
    curdate: "2016.06.16"
  },
  components: {},
  methods: {
    __find: function (inputQuery, pagenum, pagesteps) {
      var self = this;
      self.$set('pagenum', pagenum);
      svc.find('', pagenum, pagesteps, this.items, function (data, status, request) {
        var a = Object.keys(data)
        //console.log(''+data[a[1]])
        var thisDate = function (curr) {
          //返回已经当前页已经分组好的数据
          var last = curr * pagenum - 1;
          last = last >= Object.keys(data).length ? (Object.keys(data).length - 1) : last;
          var obj1 = {}
          var myMap = {};
          for (var i = (curr * pagenum - pagenum); i <= last; i++) {
            obj1 = data[a[i]];
            myMap[a[i]] = obj1;
          }
          return myMap;
        };
        laypage({
          cont: 'paging', //容器。值支持id名、原生dom对象，jquery对象,
          pages: Math.ceil(Object.keys(data).length / pagenum), //总页数
          skip: true, //是否开启跳页
          skin: '#000000',
          groups: 3, //连续显示分页数
          jump: function (obj) {
            self.$set('items', thisDate(obj.curr));
          }
        });
      }, function (data, status, request) {
        alert("Probably failed to connect the backend server! Pls check your server status!");
      });
    },
    _find: function (criterion, pagenum, pagesteps) {
      var self = this;
      svc.find2(criterion, pagenum, pagesteps, function (data, status, request) {
        // self.items.length = 0;
        self.$set('items', data);
        if (self.items.length > 0) {
          self.$set("curitem", self.items[0]);
        }
      }, function (data, status, request) {
        alert("Probably failed to connect the backend server! Pls check your server status!");
      });
    },
    find: function (id) {
      var self = this;
      console.log("find3")
      svc.find3(id, function (data, status, request) {
        self.$set("item", data);
      }, function (data, status, request) {
        alert("Probably failed to connect the backend server! Pls check your server status!");
      });
    },
    backToParent: function () {
      var self = this;
      var p = this.items2.parent;
      console.log("backToParent " + p);
      //根节点
      if (p == null) {
        svc.find('', '', '', this.items, function (data, status, request) {
          self.$set('items', data);
          if (self.items.length > 0) {
            self.$set("curitem", self.items[0]);
          }
        });
      } else {
        svc.backToParent(p, function (data, status, request) {
          self.$set('items', data);
          svc.backToParent2(p, function (data2, status, request) {
            self.$set('items2', data2)
          });
        });
      }
    },
    advancedsearch: function (e) {
      console.log("advanced search");
      console.log(e.target.tagName); // "BUTTON"
      console.log(e.targetVM === this); // true

      var inputs = new Array();
      inputs[0] = "{criterion:'";
      inputs[1] = this.criterion;
      inputs[2] = "', pagenum:'";
      inputs[3] = this.pagenum;
      inputs[4] = "', pagesteps:'";
      inputs[5] = this.pagesteps;
      inputs[6] = "', searchQuery:'";
      inputs[7] = this.searchQuery;
      inputs[8] = "'}";

      var inputQuery = inputs.join('');
      console.log("your input query condition is " + inputQuery);
      this._find(this.criterion, this.pagenum, this.pagesteps);
    },
    init: function () {
      svc.init();
      var datetime = new Date();
      datetime.getYear();        //获取当前年份(2位)
      datetime.getFullYear();    //获取完整的年份(4位,1970-????)
      datetime.getMonth();       //获取当前月份(0-11,0代表1月)
      datetime.getDate();        //获取当前日(1-31)
      datetime.getDay();         //获取当前星期X(0-6,0代表星期天)
      datetime.getTime();        //获取当前时间(从1970.1.1开始的毫秒数)
      datetime.getHours();       //获取当前小时数(0-23)
      datetime.getMinutes();     //获取当前分钟数(0-59)
      datetime.getSeconds();     //获取当前秒数(0-59)
      datetime.getMilliseconds();    //获取当前毫秒数(0-999)
      datetime.toLocaleDateString();     //获取当前日期
      this.curdate = datetime.toLocaleTimeString();     //获取当前时间
    },
    onSave: function (mode, item) {
      var uid = null;
      var self = this;
      console.log("onSave");

      if (mode == 'modeAddNew') {
        svc.add(item, function (data, status, request) {
          self.__find('', vm.pagenum, 6);
        }, function (data, status, request) {
          alert("onSave failed to update!");
        });
        this.curitem = {};
        this.setMode('modeList');
      }
      else {
        console.log("onEdit");
        svc.edit(item.id, item, function (item, status, request) {
          alert("修改成功")
        }, function (item, status, request) {
          alert("onSave failed to update!");
        });
      }
      setTimeout(function () {
        self.setMode('modeList');
      }, 20);
    },
    onCancel: function (mode, item) {
      console.log("onCancel");
      this.curitem = {};
      this.setMode('modeList');
    },
    onEdit: function (item, e) {
      console.log('editItem onEdit: ' + item.id);
      console.log('editItem onEdit item: ' + item);
      this.curitem = item;
      this.setMode('modeEdit');
    },
    onRemove: function (item, e) {
      console.log('onRemove' + item);
    },

    onRemoveItem: function (item, e) {
      this.setMode('modeList');
      var self = this;
      var r = confirm("确定删除？");
      if (r == true) {
        svc.remove(item, function (data, status, request) {
            self.__find('', vm.pagenum, 6);
          }
        )
      }
    },
    onEditItem: function (item, e) {
      console.log('editItem' + item);
      svc.edit(item);
      this.curitem = {};
      this.setMode('modeList');
    },
    onRemoveSelected: function (e) {
      console.log("removeSelected: " + e);
      var items = this.items;
      for (var i in items) {
        if (items[i].selected) {
          console.log(items[i] + ' is to be deleted!!!');
          this.onRemoveItem(items[i], null);
        }
      }
    },
    setMode: function (newmode) {
      if (this.mode != newmode) {
        switch (newmode) {
          case "modeList":
            this.modeTitle = "";
            break;
          case "modeDetails":
            this.modeTitle = " [详情]";
            break;
          case "modeEdit":
            this.modeTitle = " [编辑]";
            break;
          case "modeAddNew":
            this.modeTitle = " [新增]";
            //this.curitem.id=null;
            //svc.resetItem(this.curitem);
            this.curitem.id = null;
            break;
          default:
            this.modeTitle = "";
        }
        this.mode = newmode;
      }
    }
  },
  ready: function () {
    console.log("ready function is called");
    svc.init()
    this.__find('', 5, 6);
  }
});
setTimeout(function () {
  vm.init();
}, 20);
